package com.cntcdt.api.utils;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;

public class XmppUtils {

//	private static final String host = "192.168.1.188";
	public static final String XMPP_HOST;
	public static final String XMPP_HOST_OLD;
	static{
		XMPP_HOST = ConfigReadUtils.loadConfigByConfDir("qinqinconfig.properties").getProperty("xmpphost");
		XMPP_HOST_OLD = ConfigReadUtils.loadConfigByConfDir("qinqinconfig.properties").getProperty("xmpphost_old");
	}
	
	
	/**
	 * 创建聊天服务器的帐号
	 * @param userName
	 * @param password
	 * @return
	 */
	public boolean addAccount(String userName , String password ){
		XMPPConnection connection = new XMPPConnection(XMPP_HOST);
        try {
			connection.connect();
		} catch (XMPPException e) {
			e.printStackTrace();
		}
        AccountManager accountManager = new AccountManager(connection);
		//String account = userName + "@" + XMPP_HOST;
		try {
			accountManager.createAccount(userName, password);
		} catch (XMPPException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	
	public void addContact(String user1 ,String user1Pwd, String user2 , String user2Pwd){
		String account1 = user1 + "@" + XMPP_HOST;
		String account2 = user2 + "@" + XMPP_HOST;
		try {
			XMPPConnection connection1 = new XMPPConnection(XMPP_HOST);
			connection1.connect();
			connection1.login(account1, user1Pwd);
			Roster roster = connection1.getRoster();
	        roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
	        roster.createEntry(account2, account2, new String[]{});
	        
	        XMPPConnection connection2 = new XMPPConnection(XMPP_HOST);
	        connection2.connect();
	        connection2.login(account2, user2Pwd);
			roster = connection2.getRoster();
	        roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
	        roster.createEntry(account1, account1, new String[]{});
	        
	        connection1.disconnect();
	        connection2.disconnect();
	        
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String user1 = "lcm6";
		String user2 = "lcm7";
		XmppUtils utils = new XmppUtils();
		//utils.addAccount(user1, "111111");
		//utils.addAccount(user2, "111111");
		//utils.addContact(user1, user2);
		
	}

}
